﻿using System.Collections.Generic;
using System.Linq;

namespace ALinq.Web.Security
{
    public partial class Role
    {
        public IEnumerable<User> Users
        {
            get { return UserRoles.Select(o => o.User); }
        }

        //public IEnumerable<Territory> Territories
        //{
        //    get { return this.RoleTerritoryPermissions.Select(o => o.Territory); }
        //}

        //public IEnumerable<Permission> Permissions
        //{
        //    get
        //    {
        //        var items = RoleTerritoryPermissions.Select(o => o.Permission);
        //        return items;
        //    }
        //}

        //public IEnumerable<Permission> GetPermissions(int territoryID)
        //{
        //    var items = RoleTerritoryPermissions.Where(o => o.TerritoryID == territoryID)
        //        .Select(o => o.Permission);
        //    return items;
        //}

        //public IEnumerable<Permission> GetPermissions(Territory territory, bool includeInherit)
        //{
        //    var territoryIDs = new List<int> { territory.ID };

        //    if (includeInherit)
        //    {
        //        var parent = territory.Parent;
        //        while (parent != null)
        //        {
        //            territoryIDs.Add(parent.ID);
        //            parent = parent.Parent;
        //        }
        //    }

        //    var q = from roleTerritoryPermissions in RoleTerritoryPermissions
        //            where territoryIDs.Contains(roleTerritoryPermissions.TerritoryID)
        //            group roleTerritoryPermissions by roleTerritoryPermissions.TerritoryID
        //            into g
        //                select new
        //                           {
        //                               TerritoryID = g.Key,
        //                               Permissions = g.Select(o => o.Permission).ToList()
        //                           };

        //    IEnumerable<Permission> result = new List<Permission>();
        //    foreach (var territoryID in territoryIDs)
        //    {
        //        var item = q.Where(o => o.TerritoryID == territoryID).SingleOrDefault();
        //        if (item != null)
        //            result = result.Union(item.Permissions);
        //    }
        //    return result;
        //}
    }
}